// src/app/workspace/[workspaceId]/channel/[channelId]/_components/chat-input.tsx
'use client';
import React, {useEffect, useRef, useState} from 'react';
// import Editor from "@/components/editor";
import dynamic from 'next/dynamic'
import Quill from "quill";
import {useCreateMessage} from "@/features/messages/api/use-create-message";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useChannelId} from "@/hooks/social/use-channel-id";
import {toast} from "sonner";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";
import {useCurrentUser} from "@/hooks/use-current-user";
import {useRouter} from "next/navigation";


const Editor = dynamic(() =>
    import('@/components/social/editor'), {ssr: false}
);

interface Props {
    placeholder: string
    // 用于触发页面更新: 无效
    // setMessages: Function
}

type CreateMessageValues = {
    channelId: string
    userId: string
    workspaceId: string
    body: string
    image: string
}

const ChatInput = ({placeholder}: Props) => {
    const router = useRouter()
    const user = useCurrentUser()

    const editorRef = useRef<Quill | null>(null)
    const [editorKey, setEditorKey] = useState(0)
    const [isPending, setIsPending] = useState(false)

    const workspaceId = useWorkspaceId()
    const channelId = useChannelId()

    const {mutate: createMessage} = useCreateMessage();

    if (!workspaceId || !channelId) return

    const {mutate: generateUploadUrl} = useGenerateUploadUrl()

    const handleSubmit = async ({
                                    body, image
                                }: {
        body: string,
        // image: File | null
        image: string | null
    }) => {
        try {
            setIsPending(true)
            editorRef?.current?.enable(false)

            const values: CreateMessageValues = {
                channelId, workspaceId, body,
                userId: user?.id!,
                image: image as string
            }

            // 我在editor里的image input中直接转为base64了, 这里不需要创建url
            // if (image) {
            //     const url = await generateUploadUrl({image}, {
            //         throwError: true,
            //     })
            //     if(!url) throw new Error(`Url not found: ${url}`)
            // }

            await createMessage(values, {
                throwError: true
            })
            // @ts-ignore
            // setMessages(prev => [
            //     ...prev,
            //     message
            // ])
            setEditorKey((prevKey) => prevKey + 1)

            // editorRef?.current?.setContents([])}
        } catch (e) {
            toast.error('Failed to send message')
        } finally {
            setIsPending(false)
            editorRef?.current?.enable(true)
            window.location.reload()
        }
    }

    return (
        <div className={`px-5 w-full`}>
            <Editor
                key={editorKey}
                // variant={'update'}
                placeholder={placeholder}
                // @ts-ignore
                onSubmit={handleSubmit}
                disabled={isPending}
                innerRef={editorRef}
            />
        </div>
    );
};

export default ChatInput;